package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.oss.OssProperties;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.UUIDUtils;
import com.nineclock.message.enums.MessageTypeEnum;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.system.dto.SysAllowedJoinCompanyUserDTO;
import com.nineclock.system.dto.SysApplyJoinCompanyUserDTO;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.mapper.SysCompanyMapper;
import com.nineclock.system.mapper.SysCompanyUserMapper;
import com.nineclock.system.mapper.SysUserMapper;
import com.nineclock.system.pojo.SysCompany;
import com.nineclock.system.pojo.SysCompanyUser;
import com.nineclock.system.pojo.SysUser;
import com.nineclock.system.service.SysCompanyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class SysCompanyServiceImpl implements SysCompanyService {


    @Autowired
    SysCompanyUserMapper companyUserMapper;

    @Autowired
    SysCompanyMapper companyMapper;

    @Autowired
    SysUserMapper userMapper;

    @Override
    public List<SysCompanyDTO> queryUserJoinCompany(Long userId) {
        LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
        companyUserQw.eq(SysCompanyUser::getUserId, userId);

        //根据用户id获取企业员工列表
        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserQw);

        if(CollectionUtil.isEmpty(companyUserList)){
            throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }
        /**
         * stream ：把 集合转换为 流
         * map： 结果映射
         * collect: 转换的目标
         */
        //获取企业id
        List<Long> companyIds = companyUserList.stream().map(sysCompanyUser -> {
            return sysCompanyUser.getCompanyId();
        }).collect(Collectors.toList());

        //根据企业id获取企业列表
        LambdaQueryWrapper<SysCompany> companyQw = new LambdaQueryWrapper<>();
        companyQw.in(SysCompany::getId, companyIds);

        List<SysCompany> companyList = companyMapper.selectList(companyQw);

        List<SysCompanyDTO> companyDTOList = BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);

        return companyDTOList;
    }

    @Override
    public SysCompanyDTO queryCompanyInfo() {
        //获取企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //根据企业id获取企业信息
        SysCompany company = companyMapper.selectById(companyId);

        if(company == null){
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        //转换为dto
        SysCompanyDTO companyDTO = BeanHelper.copyProperties(company, SysCompanyDTO.class);

        return companyDTO;
    }

    @Autowired
    OSS oss;

    @Autowired
    OssProperties ossProperties;

    @Override
    public String uploadOSS(MultipartFile file) throws IOException {
        //健壮性的判断
        if(file == null){
            throw new NcException(ResponseEnum.FILE_NOT_FOUND);
        }

        //判断文件的类型
        String contentType = file.getContentType();
        if(! NcConstant.ALLOWED_IMG_TYPES.contains(contentType)){
            throw new NcException(ResponseEnum.INVALID_FILE_TYPE);
        }

        //判断文件的大小
        if(file.getSize() > NcConstant.maxFileSize){
            throw new NcException(ResponseEnum.FILE_SIZE_EXCEED_MAX_LIMIT);
        }

        //获取文件的后缀名
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成唯一的文件名  kjafllasdjflasdjfl3rrwe93248032
        String key = UUIDUtils.getUUID() + substring;

        InputStream input = file.getInputStream();
        //上传文件
        PutObjectResult putObjectResult = oss.putObject(ossProperties.getBucketName(), key, input);
        //输出上传文件的相应信息
        log.info(putObjectResult.getResponse() + "");


        //生成 图片的 外链路径:  https:// bucketname + . + endpoint + 图片名称
        String impPath = String.format(ossProperties.getHost(), ossProperties.getBucketName()) + key;
        log.info("图片路径为：" + impPath);
        return impPath;
    }

    @Override
    public void updateCompanyInfo(SysCompanyDTO sysCompanyDTO) {
        if(sysCompanyDTO == null || sysCompanyDTO.getName() == null || sysCompanyDTO.getLogo() == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //从线程中获取企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();
        //根据企业获取企业对象
        SysCompany company = companyMapper.selectById(companyId);
        if(company == null){
            throw new NcException(ResponseEnum.COMPANY_NOT_FOUND);
        }
        //更新企业信息
        company.setLogo(sysCompanyDTO.getLogo());
        company.setName(sysCompanyDTO.getName());

        //更新数据库
        companyMapper.updateById(company);
    }

    /**
     * 根据关键字 模糊查询企业信息
     * @param keyword
     * @return
     */
    @Override
    public List<SysCompanyDTO> queryCompanyByName(String keyword) {
        if(keyword == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<SysCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(SysCompany::getName, keyword);

        List<SysCompany> companyList = companyMapper.selectList(wrapper);

        if(companyList != null){
            List<SysCompanyDTO> companyDTOList = BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);
            return companyDTOList;
        }

        return new ArrayList<>();
    }


    @Autowired
    RocketMQTemplate rocketMQTemplate;
    /**
     * 申请加入企业
     *
     * 1. 健壮性的判断
     * 2. 完善user信息
     * 3. 新增员工信息
     *
     * @param applyJoinCompanyUserDTO
     */
    @Override
    public void applyJoinCompany(SysApplyJoinCompanyUserDTO applyJoinCompanyUserDTO) {
        if(applyJoinCompanyUserDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //根据userid获取用户对象
        SysUser user = userMapper.selectById(applyJoinCompanyUserDTO.getUserId());
        if(user == null){
            throw new NcException(ResponseEnum.USER_NOT_FOUND);
        }

        user.setUsername(applyJoinCompanyUserDTO.getUserName());
        user.setLastLoginCompanyId(applyJoinCompanyUserDTO.getCompanyId());
        user.setEmail(applyJoinCompanyUserDTO.getEmail());
        user.setUpdateTime(new Date());
        //更新 user信息
        userMapper.updateById(user);


        //添加员工信息
        SysCompanyUser companyUser = new SysCompanyUser();
        companyUser.setCompanyName(applyJoinCompanyUserDTO.getCompanyName()); //企业名称
        companyUser.setCompanyId(applyJoinCompanyUserDTO.getCompanyId());//企业id
        companyUser.setUserId(applyJoinCompanyUserDTO.getUserId()); //用户id
        companyUser.setEnable((short)0); //是否可以用
        companyUser.setCreateTime(new Date()); //创建时间
        companyUser.setRemark(applyJoinCompanyUserDTO.getApplyReason());//申请理由
        companyUser.setEmail(applyJoinCompanyUserDTO.getEmail()); //邮箱
        companyUser.setPost(applyJoinCompanyUserDTO.getPost()); //职务
        companyUser.setMobile(applyJoinCompanyUserDTO.getMobile()); //手机号码
        companyUser.setUserName(applyJoinCompanyUserDTO.getUserName()); //用户名
        companyUser.setImageUrl(applyJoinCompanyUserDTO.getImageUrl()); //图片路径
        companyUser.setTimeEntry(new Date()); //入职时间
        //添加员工信息到数据库
        companyUserMapper.insert(companyUser);
        //-------------------- 完成了员工的注册 ---------------------
        //推送 给管理员

        SysCompanyUser currentAdmin = companyUserMapper.queryCurrentAdmin(applyJoinCompanyUserDTO.getCompanyId());

        //封装massage
        NcMessage message = new NcMessage();
        message.setMessageType(MessageTypeEnum.COMPANY_APPLY.getType()); //消息类型 ：团队申请
        message.setApplyUserId(user.getId()); //apply  申请人
        message.setApplyUsername(companyUser.getUserName());

        message.setApproveUserId(currentAdmin.getUserId()); //审批人id (系统主管理员)
        message.setApproveUsername(currentAdmin.getUserName()); //审批人用户名
        message.setApproveStatue(0);


        message.setTargets(Arrays.asList(currentAdmin.getMobile())); //推送的目标 别名(管理员的手机号码)
        message.setContent(companyUser.getUserName() +"申请加入企业,请及时审批!!" ); //推送的内容

        message.setUseStatus(0);
        message.setAudience(MessageTypeEnum.COMPANY_APPLY.getAudience());
        message.setTitle(MessageTypeEnum.COMPANY_APPLY.getTitle());
        message.setCreateTime(new Date());
        message.setCompanyId(applyJoinCompanyUserDTO.getCompanyId() + "");

        // 推送消息到mq
        rocketMQTemplate.convertAndSend("messagePushTopic", message );
    }

    /**
     * 审核加入企业
     * 1. 健壮性判断
     * 2. 更新员工的状态
     * 3. 存储信息到mongodb, 更新mongodb信息的状态
     * 4. 推送消息给申请人
     * @param allowedJoinCompanyUserDTO
     */
    @Override
    public void allowedJoinCompany(SysAllowedJoinCompanyUserDTO allowedJoinCompanyUserDTO) {
        if(allowedJoinCompanyUserDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        //根据id查询员工对象
        SysCompanyUser companyUser = companyUserMapper.selectById(allowedJoinCompanyUserDTO.getApplyUserId());

        //更新信息
        companyUser.setRemark(allowedJoinCompanyUserDTO.getRemark());
        if(allowedJoinCompanyUserDTO.getApproved()){
            companyUser.setEnable((short)1);
        }
        //更新员工的信息
        companyUserMapper.updateById(companyUser);

        //已经审批通过
        if(allowedJoinCompanyUserDTO.getApproved()){
            //推送申请人
            NcMessage message = new NcMessage();
            message.setMessageType(MessageTypeEnum.COMPANY_APPLY_PASS.getType());
            message.setApplyUserId(allowedJoinCompanyUserDTO.getApplyUserId());
            message.setApplyUsername(companyUser.getUserName());
            message.setApproveUserId(CurrentUserHolder.get().getCompanyUserId());
            message.setApproveUsername(CurrentUserHolder.get().getUsername());
            message.setApproveStatue(1);
            message.setTargets(Arrays.asList(companyUser.getMobile()));
            message.setUseStatus(1);
            message.setAudience(MessageTypeEnum.COMPANY_APPLY_PASS.getAudience());
            message.setTitle(MessageTypeEnum.COMPANY_APPLY_PASS.getTitle());
            message.setCreateTime(new Date());
            message.setCompanyId(CurrentUserHolder.get().getCompanyId() + "");
            message.setContent("您的加入企业申请已经通过!!");

            rocketMQTemplate.convertAndSend("messagePushTopic",message);


            //推送一条 ，目的更新信息 状态
            rocketMQTemplate.convertAndSend("allowedJoinCompanyTopic",allowedJoinCompanyUserDTO.getNotifyMsgId());

        }




    }


}
